<template>
  <div class="blog-comment-container">
    <div>
      <MessageArea title="评论列表" :subTitle="data.total + ''" :list="data.rows" :isListLoading="isLoading" @submit="handleSubmit" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, computed, onUnmounted, onMounted, type ComponentPublicInstance } from 'vue'
import { getComments, postComment } from '@/api/blog'
import { useRouter } from 'vue-router'
import type { getCommentsType } from '@/types/blog'
const router = useRouter()
const proxy: ComponentPublicInstance<any> = getCurrentInstance()?.proxy
const data = ref<getCommentsType>({ total: 0, rows: [] })
const isLoading = ref(false)
onMounted(async () => {
  data.value = await fetchData()
})

proxy.$mybus.on('mainScroll', handleScroll)
async function handleScroll(dom: any) {
  if (isLoading.value || !dom) {
    // 目前正在加载更多
    return
  }
  const range = 100 // 顶一个可接受的范围，在这个范围内都算达到了底部
  const dec = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight)
  if (dec <= range) {
    await fetchMore()
  }
}
const page = ref(1)
const limit = ref(10)
async function fetchData() {
  isLoading.value = true
  let result = await getComments(router.currentRoute.value.params.id + '', page.value, limit.value)

  isLoading.value = false
  return result
}
const hasMore = computed(() => {
  return data.value.rows.length < data.value.total
})
// 加载下一页
async function fetchMore() {
  if (!hasMore.value) {
    // 没有更多啦
    return
  }
  page.value++
  const resp = await fetchData()
  data.value.total = resp.total
  data.value.rows = data.value.rows.concat(resp.rows)
}
async function handleSubmit(formData: any, callback: Function) {
  const resp = await postComment({
    blogId: router.currentRoute.value.params.id,
    ...formData
  })
  if (!resp) {
    callback('')
    return
  }
  data.value.rows.unshift(resp)
  data.value.total++
  callback('评论成功') // 告诉子组件，我这边处理完了，你继续
}
onUnmounted(() => {
  proxy.$mybus.off('mainScroll', handleScroll)
})
</script>

<style scoped lang="scss">
.blog-comment-container {
  margin: 30px 0;
}
</style>
